package com.speciality.demo.demos.web;

import com.speciality.demo.demos.dto.PredictionResult;
import com.speciality.demo.demos.dto.StatsResponse;
import com.speciality.demo.demos.service.WeatherPredictionService;
import lombok.RequiredArgsConstructor;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Repository;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.time.LocalDate;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/api/weather/anomaly")
@RequiredArgsConstructor
public class WeatherPredictionController {

    // 注入真实的服务层实现（Spark逻辑已在ServiceImpl中）
    private final WeatherPredictionService weatherPredictionService;


// 控制器关键逻辑（已对接服务层）
    @GetMapping("/predict")
    public ResponseEntity<List<PredictionResult>> getPredictions(
            @RequestParam @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate startDate) {
        return ResponseEntity.ok(weatherPredictionService.getWeeklyPrediction(startDate));
    }

    /**
     * 获取真实统计信息（基于真实预测结果计算）
     * 前端调用：/api/weather/anomaly/stats?
     */
    @GetMapping("/stats")
    public ResponseEntity<StatsResponse> getStats( @RequestParam("startDate") @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate startDate,
                                                   @RequestParam("endDate") @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate endDate
    ) {
        return ResponseEntity.ok(weatherPredictionService.getPredictionStats(startDate, endDate));
    }

    /**
     * 获取异常分布数据（基于真实预测结果生成图表数据）
     * 前端调用：/api/weather/anomaly/distribution?startDate=2024-01-01
     */
    @GetMapping("/distribution")
    public ResponseEntity<Map<String, Object>> getDistribution(
            @RequestParam @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate startDate) {
        // 1. 调用服务层获取真实预测结果
        List<PredictionResult> predictions = weatherPredictionService.getWeeklyPrediction(startDate);

        // 2. 基于真实预测结果，统计每日正常/异常数量（用于图表）
        Map<String, Map<String, Integer>> dailyDistribution = predictions.stream()
                .collect(Collectors.groupingBy(
                        // 按日期分组（截取时间字符串的日期部分）
                        pred -> pred.getTime().split(" ")[0],
                        Collectors.groupingBy(
                                pred -> pred.getIsAbnormal() == 1 ? "abnormal" : "normal",
                                Collectors.summingInt(e -> 1)
                        )
                ));

        // 3. 整理图表所需格式
        List<String> dates = new ArrayList<>(dailyDistribution.keySet());
        List<Integer> normalCounts = new ArrayList<>();
        List<Integer> abnormalCounts = new ArrayList<>();

        for (String date : dates) {
            Map<String, Integer> countMap = dailyDistribution.get(date);
            normalCounts.add(countMap.getOrDefault("normal", 0));
            abnormalCounts.add(countMap.getOrDefault("abnormal", 0));
        }

        Map<String, Object> chartData = new HashMap<>();
        chartData.put("dates", dates);
        chartData.put("normalCounts", normalCounts);
        chartData.put("abnormalCounts", abnormalCounts);

        return ResponseEntity.ok(chartData);
    };
}
